<?php

define('RUN_ENV', isset($_SERVER['RUNTIME_ENVIROMENT']) ? $_SERVER['RUNTIME_ENVIROMENT'] : 'dev');
require_once (dirname(__FILE__) . '/../../../data/' . RUN_ENV . '/config.php');

class JSSDK
{
    private $appId;
    private $appSecret;
    public $access_token;

    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->access_token = $this->getAccessToken();
    }

    public function getSignPackage($url)
    {
        $jsapiTicket = $this->getJsApiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode.
//        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
//        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"."?rec=shipment";
//    $url = "http://site.100mzhan.cn/bmz/m/index.php";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string,
            'jsapi_ticket' =>$jsapiTicket//测试签名是否错误
        );

        return $signPackage;
    }
    /**
     * 生成随机字符串 16位
     */
    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    public function getJsApiTicket()
    {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $object =  json_decode(file_get_contents(JSAPI_TICKET_PATH . 'jsapi_ticket'),true);
        if($object['errcode'] == '40001' || time() - $object['time'] >= $object['expires_in'] - 600){
            \MyLog::info("ACCESSTOKEN_ERROR  DELETE_JSAPI_TICKET ===> FAILURE  <=== RES= ". serialize($object));
            // 删除 jsapi_ticket 文件,access_token 也删除
            unlink(ACCESS_TOKEN_PATH . 'access_token');
            unlink(JSAPI_TICKET_PATH . 'jsapi_ticket');
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            MyLog::info('NEW_JSSDK_RECV_WX_JSAPI_TICKET 1 <===' . $url . ' <=== ' . serialize($res));
            $res->time = time();
            $resJson = json_encode($res);
            $ticket = $res->ticket;
            if ($resJson) {
                $fp = fopen(JSAPI_TICKET_PATH . 'jsapi_ticket', "w");
                fwrite($fp, $resJson);
                fclose($fp);
            }
        }
        $data = json_decode(file_get_contents(JSAPI_TICKET_PATH . 'jsapi_ticket'));
        \MyLog::info('JSSDK_READ_WX_JSAPI_TICKET ===> filename=' . JSAPI_TICKET_PATH . 'jsapi_ticket' . ' <=== ' .serialize($data));
        if (time() - $data->time >= $data->expires_in - 600) {
            for($i=0; $i<2; $i++){//循环两次
                $accessToken = $this->getAccessToken();
                // 如果是企业号用以下 URL 获取 ticket
                // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
                $res = json_decode($this->httpGet($url));
                if ($res['errcode'] == 0 && $res['errmsg'] == 'ok') {
                    MyLog::info('JSSDK_RECV_WX_JSAPI_TICKET <===' . $url . ' <=== ' . serialize($res));
                    $res->time = time();
                    $resJson = json_encode($res);
                    $ticket = $res->ticket;
                    if ($resJson) {
                        $fp = fopen(JSAPI_TICKET_PATH . 'jsapi_ticket', "w");
                        fwrite($fp, $resJson);
                        fclose($fp);
                    }
                    return $ticket;
                } else {
                    \MyLog::info("ACCESS_TOKEN_ERROR ===> FAILURE, access_token=" . $access_token . ' <=== RES=' . serialize($res));
                    // 删除access token文件
                    unlink(JSAPI_TICKET_PATH . 'jsapi_ticket');
                }
                
            }
        } else {
            $ticket = $data->ticket;
        }
        return $ticket;
    }

    public function getAccessToken()
    {
        // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents(ACCESS_TOKEN_PATH . 'access_token'));
        \MyLog::info('JSSDK_READ_WX_ACCESS_TOKEN ===> filename=' . ACCESS_TOKEN_PATH . 'access_token' . ' <=== ' .serialize($data));
        if (time() - $data->time >= $data->expires_in - 600) {
            // 过期
            // 如果是企业号用以下URL获取access_token
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            MyLog::info('JSSDK_RECV_WX_ACCESS_TOKEN <===' . $url . ' <=== ' . serialize($res));
            $res->time = time();
            $resJson = json_encode($res);
            $access_token = $res->access_token;
            if ($resJson) {
                $fp = fopen(ACCESS_TOKEN_PATH . 'access_token', "w");
                fwrite($fp, $resJson);
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
    /*下载图片*/
    public function downlodimg($serverId){
        $access_token = $this->getAccessToken();
        // /bmz/public/img/2222.jpg
        $images_name = rand(1,100).date('YmdHis').'.jpg';
        $targetName=dirname(dirname(dirname(__FILE__))).'/../public/img/'. $images_name;
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serverId}";
        $ch=curl_init($url);// 初始化
        file_put_contents('urlres.log', $url);
        $fp=fopen($targetName, 'wb');// 打开写入
        curl_setopt($ch, CURLOPT_FILE, $fp);// 设置输出文件的位置，值是一个资源类型
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $res = curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return  $images_name;
    }
    /*洗车下载图片*/
    public function wash_downlodimg($serverId){
        $access_token = $this->getAccessToken();
        // /bmz/public/img/2222.jpg    substr(microtime(),2,4)
        $images_name = rand(10,99).date('YmdHis').substr(microtime(),2,4).rand(1000,9999).'.jpg';
        // $images_name = rand(1,100).date('YmdHis').'.jpg';
        $targetName=dirname(dirname(dirname(__FILE__))).'/../public/wash_imgs/'. $images_name;
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serverId}";
        $ch=curl_init($url);// 初始化
        file_put_contents('urlres.log', $url);
        $fp=fopen($targetName, 'wb');// 打开写入
        curl_setopt($ch, CURLOPT_FILE, $fp);// 设置输出文件的位置，值是一个资源类型
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $res = curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return  $images_name;
    }
    /*个人中心 下载图片*/
    public function user_center_downlodimg($serverId){
        $access_token = $this->getAccessToken();
        // /bmz/public/img/2222.jpg
        $images_name = rand(1,100).date('YmdHis').'.jpg';
        $targetName=dirname(dirname(dirname(__FILE__))).'/../m/user_center/theme/default2/images/'. $images_name;
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serverId}";
        $ch=curl_init($url);// 初始化
        file_put_contents('urlres.log', $url);
        $fp=fopen($targetName, 'wb');// 打开写入
        curl_setopt($ch, CURLOPT_FILE, $fp);// 设置输出文件的位置，值是一个资源类型
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $res = curl_exec($ch);
        curl_close($ch);
        fclose($fp);
        return  $images_name;
    }
}